<?php

namespace App\Http\Controllers\Api;

use GuzzleHttp\Exception\RequestException;
use function GuzzleHttp\Psr7\str;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use App\Http\Controllers\ApiController;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\UnauthorizedException;
use Validator;
use GuzzleHttp\Client;
use App\Models\PickupUser;

class PickupUserController extends ApiController
{

    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */

    use AuthenticatesUsers;

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
//        $this->middleware('guest')->except('logout');
    }

    /**
     * 获取登录TOKEN
     * @param LoginRequest $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function login(Request $request)
    {
        $mobile = $request->input('mobile');
        $password = $request->input('password');
        $pickup_user = PickupUser::Where('mobile', $mobile)->first();
        if (empty($pickup_user)) {
            return $this->failed("账号或密码错误");
        }

        if ($pickup_user->status == 0) {
            return $this->failed("账号已被禁用");
        }

        $client = new Client();
        try {
            $url = request()->root() . '/api/oauth/token';

            $params = array_merge(config('passport.proxy'), [
                'username' => $mobile,
                'password' => $password,
                'guard'    => 'pickup_api'
            ]);
            $respond = $client->request('POST', $url, ['form_params' => $params]);
        } catch (RequestException $e) {
            return $this->failed("账号验证失败");
        }

        if ($respond->getStatusCode() == 401) {
            return $this->failed("账号验证失败");
        }
        $token = json_decode($respond->getBody()->getContents(), true);
        $data['token'] =  $token['access_token'];
        $data['user'] = ['is_pwd_reset' => $pickup_user->is_pwd_reset];
        return $this->success($data);
    }

    /**
     * 退出登录
     */
    public function logout()
    {
        if (\Auth::guard('pickup_api')->check()) {
            \Auth::guard('pickup_api')->user()->token()->delete();
        }

        return $this->success("退出成功");
    }

    /**
     * 修改密码
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function modifyPassword(Request $request)
    {
        $user = \Auth::guard('pickup_api')->user();
        $old_password = $request->input("old_password", "");
        $new_password = $request->input("new_password", "");
        if (!\Hash::check($old_password, $user->password)) { //原始密码和数据库里的密码进行比对
            return $this->failed("原密码不正确");
        }
        if(!preg_match("/^\w{6,18}$/", $new_password)) {
            return $this->failed("新密码只能包含字母，数字和下划线，长度为6至18位");
        }
        $res = DB::table('pickup_user')->where('id', $user->id)->update(array('password' => bcrypt($new_password), 'is_pwd_reset' => 1));
        if ($res === false) {
            return $this->failed("修改密码失败");
        }
        return $this->success("修改密码成功");
    }


    /**
     * 找回密码
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function findPassword(Request $request)
    {
        $mobile = $request->input("mobile", "");
        $verify_code = $request->input("verify_code", "");
        $password = $request->input("password", "");

        //验证用户输入
        if (empty($mobile)) {
            return $this->failed("手机号不能为空");
        }
        if (empty($verify_code)) {
            return $this->failed("验证码不能为空");
        }
        if (empty($password)) {
            return $this->failed("新密码不能为空");
        }

        if(!preg_match("/^1[3456789]\d{9}$/", $mobile)) {
            return $this->failed("手机号格式不正确");
        }

        //查找手机号是否已注册
        $user_is_exist = DB::table('pickup_user')->where('mobile', $mobile)->first();
        if (empty($user_is_exist)) {
            return $this->failed("该用户未注册");
        }

        $type = 3; //忘记密码
        $send_code_key = "user_send_code_{$type}_{$mobile}";

        if($verify_code != Cache::get($send_code_key)) {
            return $this->failed("验证码不正确");
        }

        if(!preg_match("/^\w{6,18}$/", $password)) {
            return $this->failed("密码只能包含字母，数字和下划线，长度为6至18位");
        }


        //验证通过后修改密码
        $user_res = DB::table('pickup_user')->where('id', $user_is_exist->id)->update(array('password' => bcrypt($password), 'is_pwd_reset' => 1));
        if ($user_res === false) {
            return $this->failed("找回密码失败");
        }
        Cache::forget($send_code_key);
        return $this->success("找回密码成功");
    }

    /**
     * 订单核销历史
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function checkHistory(Request $request)
    {
        $user = \Auth::guard('pickup_api')->user();
        $user_id = $user->id;
        $site_id = $user->site_id;
        $page = $request->input("page", 1);
        $limit = $request->input("limit", 10);

        if ($page <= 0) {
            return $this->failed("参数错误");
        }
        if ($limit <= 0 || $limit > 100) {
            return $this->failed("参数错误");
        }
        $site_name = DB::table('pickup_site')->where(['id' => $site_id])->value('name');
        $order_list = DB::table('pickup_check_history AS c')
            ->leftJoin('shopping_order AS o', 'o.id', '=', 'c.order_id')
            ->leftJoin('user AS u', 'u.id', '=', 'o.user_id')
            ->where(['c.user_id' => $user_id])
            ->select('o.id', 'o.order_no','o.goods_num', 'o.is_fresh', 'o.money', 'o.status', 'o.order_time', 'u.mobile as mobile')
            ->skip($limit * ($page -1))
            ->take($limit)
            ->get();

        if (!empty($order_list)) {
            $order_ids = [];
            foreach ($order_list as $list) {
                $order_ids[] = $list->id;
            }
            $order_items = DB::table('shopping_order_items AS i')
                ->leftJoin('goods AS g', 'g.id', '=', 'i.goods_id')
                ->whereIn('i.order_id', $order_ids)
                ->select('i.order_id', 'i.goods_id', 'i.goods_num', 'i.goods_price', 'g.main_pic')
                ->get();
            foreach ($order_list as $key => $order) {
                foreach ($order_items as $item)
                {
                    if ($order->id == $item->order_id) {
                        $order_list[$key]->goods_list[] = $item;
                    }
                }
            }
        } else {
            $order_list = [];
        }

        $count =  DB::table('pickup_check_history')->where(['user_id' => $user_id])->count();
        return $this->success(['site_name' => $site_name, 'order_list' => $order_list, 'more' => $count > $page * $limit ? true : false]);
    }

    /**
     * 扫码核销
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function checkOrder(Request $request)
    {
        $user = \Auth::guard('pickup_api')->user();
        $user_id = $user->id;
        $site_id = $user->site_id;
        $check_code = $request->input("code");
        $check_code = explode("_", $check_code);
        if (!is_array($check_code)) {
            return $this->success("参数错误");
        }
        $order_no = $check_code[0];
        $md5_code = $check_code[1];
        $order = DB::table('shopping_order')->where(['order_no' => $order_no])->first();
        if (empty($order)) {
            return $this->failed("订单不存在");
        }
        if ($order->site_id != $site_id) {
            return $this->failed("您没有权限核销");
        }
        if ($order->status != 2) {
            return $this->failed("订单不是未领取状态");
        }
        if (md5($order_no . md5($order->check_code)) != $md5_code) {
            return $this->failed("订单错误");
        }
        if ($order->is_fresh) {
            $now_time = time();
            if($now_time < $order->start_pick_time) {
                return $this->failed("还未到领取时间");
            } elseif ($now_time > $order->end_pick_time) {
                return $this->failed("已超过领取时间");
            }
        }

        DB::beginTransaction();
        $history_res = DB::table('pickup_check_history')->insert([
            'site_id' => $site_id,
            'user_id' => $user_id,
            'order_id' => $order->id,
            'check_time' => $now_time
        ]);
        $order_res = DB::table('shopping_order')->where(['id' => $order->id])->update([
            'status' => 3,
            'success_time' => $now_time
        ]);
        if (empty($history_res) && empty($order_res)) {
            DB::rollBack();
            return $this->failed("核销失败");
        }
        DB::commit();

        return $this->success(['order' => ['money' => $order->money, 'order_no' => $order_no, 'check_time' => $now_time]]);
    }
}
